package com.xsm.activitygroup;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import cn.bidaround.youtui_template.YtTemplate;
import cn.bidaround.ytcore.login.AuthListener;
import cn.bidaround.ytcore.login.AuthLogin;
import cn.bidaround.ytcore.login.AuthUserInfo;

import com.umeng.analytics.MobclickAgent;
import com.xsm.DataBase.initDataBase;
import com.xsm.activitygroup.R;
import com.xsm.internet.PostMessage;
import com.xsm.object.BookObject;
import com.xsm.view.ClearEditText;
import com.xsm.view.LoadDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity{
	ClearEditText user,password;
	LoginHandler handler;
	String result="-1";
	Context context;
	private TextView entoTextView,NoLogin,Title;
	LoadDialog dialog;
	CheckBox isremeber;
	String otherid="";
	String userid="";
	String sex="";
	String icon="";
	String name="";
	
protected void onCreate(Bundle savedInstanceState) {
   requestWindowFeature(Window.FEATURE_NO_TITLE); 
	super.onCreate(savedInstanceState);
	 YtTemplate.init(this);/*初始化友推*/
	setContentView(R.layout.login);
	handler=new LoginHandler();
	context=this;
	initView();
}

private void  initView(){
	// 获取packagemanager的实例
    PackageManager packageManager = getPackageManager();
    // getPackageName()是你当前类的包名，0代表是获取版本信息
    PackageInfo packInfo;
    String version="";
	try {
		packInfo = packageManager.getPackageInfo(getPackageName(),0);
		 version = packInfo.versionName;	 
	} catch (NameNotFoundException e) {
	}
	SharedPreferences sharedPreferences=getSharedPreferences("xsm", 0);
	isremeber=(CheckBox)findViewById(R.id.isremeber);
	user=(ClearEditText)findViewById(R.id.user);
	password=(ClearEditText)findViewById(R.id.password);
	NoLogin=(TextView)findViewById(R.id.nologin);
	Title=(TextView)findViewById(R.id.title);
	Title.setText("v"+version);
	NoLogin.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
	NoLogin.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			startActivity(new Intent(context,Nologin.class));
		}
	});
	
	entoTextView=(TextView)findViewById(R.id.ento);
	entoTextView.setText(getString(R.string.Ento));
	entoTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
	entoTextView.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
     startActivity(new Intent(context,MainActivity.class));
      finish();
		}
	});
}

protected void onDestroy() {
	// 调用
	YtTemplate.release(this);
	super.onDestroy();
}
public void qqlogin(View view){
	final AuthLogin qqLogin = new AuthLogin() {
		public void onAuthComplete() {
		}
	};
	AuthListener listener = new AuthListener() {
		public void onAuthCancel(Activity arg0) {
		}
		public void onAuthFail(Activity arg0) {
		}
		public void onAuthSucess(Activity arg0, final AuthUserInfo arg1) {
			otherid=arg1.getQqOpenid();
			sex=arg1.getQqGender();
			name=arg1.getQqNickName();
			icon=arg1.getQqImageUrl();
			 checkinfo();
		}
	};
	qqLogin.qqAuth(this, listener);
}

public void tengxunact(View view){
	final AuthLogin txLogin = new AuthLogin() {
		public void onAuthComplete() {
		}
	};
	AuthListener listener = new AuthListener() {
		public void onAuthCancel(Activity arg0) {
		}
		public void onAuthFail(Activity arg0) {
		}
		public void onAuthSucess(Activity arg0, final AuthUserInfo arg1) {
			otherid=arg1.getTencentWbOpenid();
			sex=arg1.getTencentWbGender();
			name=arg1.getTencentWbName();
			icon=arg1.getTencentWbHead();
			 checkinfo();
			 Toast.makeText(context, otherid, Toast.LENGTH_LONG).show();Log.d("my",otherid);
		}};
     txLogin.tencentWbAuth(this, listener);
}

public void xinlangact(View view){
	final AuthLogin xlLogin = new AuthLogin() {
		public void onAuthComplete() {
		}
	};
	AuthListener listener = new AuthListener() {
		public void onAuthCancel(Activity arg0) {
		}
		public void onAuthFail(Activity arg0) {
		}
		public void onAuthSucess(Activity arg0, final AuthUserInfo arg1) {
			otherid=arg1.getSinaUid();		
			name=arg1.getSinaName();
			sex=arg1.getSinaGender();
			icon=arg1.getSinaProfileImageUrl();
			 checkinfo();
		}};
		xlLogin.sinaAuth(this, listener);
}
private void checkinfo(){
	 dialog=new LoadDialog(context, "正在登陆...");
	 dialog.showDialog();
	   final Message msg=handler.obtainMessage();
new Thread(new Runnable() {
	public void run() {
		List params=new ArrayList();
		params.add(new BasicNameValuePair("ASK","Other"));
		params.add(new BasicNameValuePair("id",otherid));
		PostMessage postMessage=new PostMessage(params);
		userid=postMessage.getResult();	
		if(userid.equals("0")){
			msg.what=3;
		}else if(userid.equals("-1")){
			msg.what=-1;
		}else{
			msg.what=4;
		}
		handler.sendMessage(msg);
	}
}).start();
}

private String isSuccess(){
	List params=new ArrayList();
	params.add(new BasicNameValuePair("ASK","Login"));
	params.add(new BasicNameValuePair("user",user.getText().toString().trim()));
	params.add(new BasicNameValuePair("password",password.getText().toString().trim()));
	PostMessage postMessage=new PostMessage(params);
	String result=postMessage.getResult();
	return result;
}


public void Login(View view){

     if(user.getText().toString().trim().equals("")){
    	Toast.makeText(context, "请输入账户", Toast.LENGTH_LONG).show();
    	user.setShakeAnimation();
    	return;
     }else if(password.getText().toString().trim().equals("")){
       Toast.makeText(context, "请输入密码", Toast.LENGTH_LONG).show();
       password.setShakeAnimation();
     	return; 
     }
     else {
    Login();
		}

}
private void Login(){
    final Message msg=handler.obtainMessage();
	 dialog=new LoadDialog(context, "正在登陆...");
	 dialog.showDialog();
	 new Thread(new Runnable() {
			public void run() {
	result=isSuccess();
    if(result.equals("-1"))
    msg.what=-1;
    else if(result.equals("1"))
    msg.what=1;
    else if(result.equals("2"))
    msg.what=2;
    else {
    msg.what=0; 
    initDataBase iDataBase=new initDataBase(context,result);
    iDataBase.creatTable();
    }
    handler.sendMessage(msg);
    
}}).start();
}

public void Register(View view){
	Intent intent=new Intent();
	intent.setClass(context,Register.class);
	intent.putExtra("type", "");
startActivityForResult(intent,1);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1)
{
if(resultCode==RESULT_OK){
user.setText(data.getExtras().getString("user"));
password.setText(data.getExtras().getString("password"));
Login();
}
}
	
}


class LoginHandler extends Handler{
public void handleMessage(Message msg) { 
	dialog.dissmissDialog();
		if(msg.what==1){
			password.setShakeAnimation();
			Toast.makeText(context,"密码错误", Toast.LENGTH_LONG).show();
		}else if(msg.what==2){
			user.setShakeAnimation();
			Toast.makeText(context,"还没注册的用户", Toast.LENGTH_LONG).show();	
		}else if(msg.what==-1){
			Toast.makeText(context,getString(R.string.neterror), Toast.LENGTH_LONG).show();
		}else if(msg.what==0){
			SharedPreferences sharedPreferences = null;
			 sharedPreferences=getSharedPreferences("XSM", 0);
			if(isremeber.isChecked()){
			sharedPreferences.edit().putString("IsLogin","yes").commit();
			}else {
			sharedPreferences.edit().putString("IsLogin","").commit();
			}
			sharedPreferences.edit().putString("User",result).commit();
			startActivity(new Intent(context,MainActivity.class));
			finish();
		}else if(msg.what==3){
			//还没注册
			Intent intent=new Intent();
			intent.setClass(context,Register.class);
			intent.putExtra("type",otherid);
			intent.putExtra("sex", sex);
			intent.putExtra("name",name);
			intent.putExtra("icon", icon);
		    startActivityForResult(intent,1);
		
		}else if(msg.what==4){
			SharedPreferences sharedPreferences=getSharedPreferences("XSM", 0);
			if(isremeber.isChecked()){
				sharedPreferences.edit().putString("IsLogin","yes").commit();
				}else {
				sharedPreferences.edit().putString("IsLogin","").commit();
				}
			    sharedPreferences.edit().putString("User", userid).commit();
		        initDataBase iDataBase=new initDataBase(context,userid);
		         iDataBase.creatTable();
				startActivity(new Intent(context,MainActivity.class));
				finish();
		}
	
}	
}

@Override
protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
@Override
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}
}
